﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using PhotoBlog.Core.Models.Blogs;
using PhotoBlog.Models;
using PhotoBlog.Models.Builders;
using PhotoBlog.Models.ClientModels;
using PhotoBlog.Models.Users;

namespace PhotoBlog.Controllers
{
    public class HomeController : Controller
    {
        private readonly IMainVmBuilder mainVmBuilder;
        private readonly IUserRepository userRepository;
        private readonly IBlogRepository blogRepository;

        public HomeController(IMainVmBuilder mainVmBuilder, IUserRepository userRepository, IBlogRepository blogRepository)
        {
            this.mainVmBuilder = mainVmBuilder;
            this.userRepository = userRepository;
            this.blogRepository = blogRepository;
        }

        public ActionResult Index()
        {
            var model = mainVmBuilder.BuildPortfolio();
            ViewBag.Url = "http://mshots.ru/";
            ViewBag.Title = "Галерея проекта 365 лиц";
            ViewBag.Description = "Фотопроект Шатихина Михаила.";
            return View(model);
        }

        public ActionResult About()
        {
            ViewBag.Url = "http://mshots.ru/about";
            ViewBag.Title = "О проекте 365 лиц";
            ViewBag.Description =
                "Обо мне. Меня зовут Михаил, по профессии я программист. Я решил запустить фотопроект — '365 лиц'. " +
                "В течение года я буду создавать и выкладывать на всеобщее обозрение по одной фотографии в день. " +
                "Героями фотографий будете вы, каждый день новое лицо!";
            return View();
        }

        [HttpGet]
        public ActionResult Posts(int? id)
        {
            ViewBag.Title = string.Format("Блог Шатихина Михаила");
            if (id.HasValue && id != 0)
            {
                var pagingM = new PagingM
                {
                    Pages = new List<int>(),
                    CurrentPage = id ?? 0,
                    HasNextPage = false,
                    HasPrevPage = false,
                    NextPage = 0,
                    PrevPage = 0
                };

                var posts = blogRepository.GetPosts(false).ToArray();
                pagingM.Pages.AddRange(posts.Select(p => p.BlogId));

                var postsLength = posts.Length;
                for (var i = 0; i < postsLength; i++)
                {
                    if (posts[i].BlogId != id.Value) continue;
                    pagingM.CurrentPage = id.Value;
                    if ((i + 1) < postsLength)
                    {
                        pagingM.NextPage = posts[i + 1].BlogId;
                        pagingM.HasNextPage = true;
                    }
                    if ((i - 1) >= 0)
                    {
                        pagingM.PrevPage = posts[i - 1].BlogId;
                        pagingM.HasPrevPage = true;
                    }
                }

                var model = new PostM
                {
                    Paging = pagingM,
                    Post = posts.SingleOrDefault(p => p.BlogId == id.Value)
                };
                ViewBag.Title = model.Post.HeaderName;
                return View("Post", model);
            }
            else
            {
                var model = new BlogM
                {
                    Posts = blogRepository.GetPosts(false).OrderByDescending(p => p.BlogId).ToArray()
                };
                return View("Blog", model);
            }
        }

        [HttpGet]
        public ActionResult Photos(int? numberDay)
        {
            if (numberDay != null && numberDay != 0)
            {
                ViewBag.NumberDay = numberDay;
                ViewBag.Url = "http://mshots.ru/day/" + numberDay;
                ViewBag.Title = "Фотодень " + numberDay.Value;
                ViewBag.Description = "";
                return View("Photo");
            }
            return View();
        }

        [HttpPost]
        public ActionResult DayPhoto(GetPhotosParams getPhotosParams)
        {
            var result = mainVmBuilder.BuildDayPhoto(getPhotosParams);
            return Json(result);
        }

        [Authorize]
        [HttpPost]
        public ActionResult SavePhoto(PhotoM photo)
        {
            var isAdmin = userRepository.UserIsAdmin(User.Identity.Name);
            if (!isAdmin)
            {
                return View("_Layout");
            }
            var result = mainVmBuilder.SavePhoto(photo);
            return Json(result);
        }

        [HttpPost]
        public ActionResult Photos(GetPhotosParams getPhotosParams)
        {
            const int defaultAlbumId = 1;

            getPhotosParams.AlbumId = defaultAlbumId;
            getPhotosParams.Take = getPhotosParams.Take;
            getPhotosParams.Skip = getPhotosParams.Skip;

            var result = mainVmBuilder.BuildPhotos(getPhotosParams);
            return Json(result);
        }

        [Authorize]
        [HttpGet]
        public ActionResult Albums()
        {
            var isAdmin = userRepository.UserIsAdmin(User.Identity.Name);
            if (!isAdmin)
            {
                return View("_Layout");
            }
            return View();
        }

        [Authorize(Users = "admin")]
        [HttpPost]
        public ActionResult Albums(int? id)
        {
            var result = mainVmBuilder.BuildAlbums();
            return Json(result);
        }

        [Authorize]
        [HttpGet]
        public ActionResult Album(int id)
        {
            var isAdmin = userRepository.UserIsAdmin(User.Identity.Name);
            if (!isAdmin)
            {
                return View("_Layout");
            }
            ViewBag.AlbumId = id;
            return View();
        }

        [Authorize(Users = "admin")]
        [HttpPost]
        public ActionResult LoadAlbum(int id)
        {
            var result = mainVmBuilder.BuildPhotoAlbums(id);
            return Json(result);
        }

    }
}
